/**
 * 包含n个reducer函数： 根据旧的state和指定的action返回一个新的state
 */
import {combineReducers} from 'redux'
import { 
        AUTH_SUCCESS,
        ERROR_MSG, 
        RESET_USER, 
        RECEIVE_USER,
        RECEIVE_USER_LIST,
        RECEIVE_MSG,
        RECEIVE_MSG_LIST,
        MSG_READ 
    } from './action-types'
import { getRedirectTo } from '../utils'

const initUser = {
    username: '',
    type: '',
    msg: '',    // 存放错误提示信息
    redirectTo: ''  // 指定需要重定向的路由路径
}
// 产生user状态的reducer
function user(state=initUser, action){
    switch(action.type){
        case AUTH_SUCCESS:
            const {type, header} = action.data
            return {...action.data, redirectTo: getRedirectTo(type, header)}
        case ERROR_MSG:
            return {...state, msg: action.data}
        case RECEIVE_USER:
            return action.data  // action.data 是user
        case RESET_USER:
            return { ...initUser, msg: action.msg}  // action.data是msg
        default:
            return state
    }
}

const initUserList = []
function userList(state=initUserList, action){
    switch (action.type){
        case RECEIVE_USER_LIST:
            return action.data
        default :
            return state 
    }
}
// 产生聊天状态的reducer
const initChat = {
    users: {},  // 所有用户信息的对象 属性名：userId, 属性值：{username， header}
    chatMsgs: [],   // 当前用户所有相关消息
    unReadCount: 0
}

function chat(state=initChat, action) {
    switch (action.type) {
        case RECEIVE_MSG_LIST:
            const {users, chatMsgs, userId} = action.data
            return {
                users,
                chatMsgs,
                unReadCount: chatMsgs.reduce((proTotal, msg)=> proTotal+(!msg.read&&msg.to===userId)?1:0, 0)
            }
        case RECEIVE_MSG:
            const {chatMsg} = action.data
            return {
                users: state.users,
                chatMsgs: [...state.chatMsgs, chatMsg],
                unReadCount: state.unReadCount + (!chatMsg.read&&chatMsg.to===action.data.userId)?1:0
            }
        case MSG_READ:
            const {from, to, count} = action.data
            return{
                users: state.users,
                chatMsgs: state.chatMsgs.map(msg=>{
                    if(msg.from===from && msg.to===to && !msg.read){
                        return {...msg, read: true}
                    }else {
                        return msg
                    }
                }),
                unReadCount: (state.unReadCount - count) <0 ? 0 : state.unReadCount - count
            }
        default:
            return state;
    }
}

export default combineReducers({
    user,
    userList,
    chat
})